<template>
    <div class="box">
        <vxe-modal v-model="showDialog" :title="title"   :maskClosable="true"  :width="isequipment?800:screenWidth" height="580" transfer lock-scroll @close="close">
              <el-main style="padding: 0 10px !important;">
                <vxe-toolbar v-if="status===0" ref="xToolbar" align="center" perfect  border size="small" style="height: auto">
                  <template #buttons>
                    <el-row style="margin: 6px 20px;display: flex;justify-content: space-between;" >
                        <el-col :span="4">  <el-button size="small" type="primary"  :icon="DocumentChecked" @click="selectFile">选择文件</el-button></el-col>
                        <el-col :span="4">  <el-button size="small" type="success"  :icon="Finished" @click="uploadFile">上传文件</el-button></el-col>
                        <el-col :span="4">  <el-button size="small" type="warning" :icon="DeleteFilled" @click="deleteFile">删除文件</el-button></el-col>
                        <el-col :span="4">  <el-button size="small" type="primary" :icon="ArrowDown" :loading="loading" :disabled="DS" @click="submit">确定返回</el-button></el-col>
                   </el-row>
                  </template>
                </vxe-toolbar>
                <vxe-table border ref="FileTable" header-align="center" :data="tableData"  height="450"  size="mini">
                  <vxe-column type="checkbox" width="40"></vxe-column>
                  <vxe-column field="fileName" width="200" title="文件名称"></vxe-column>
                  <vxe-column field="fileSize" width="90" :formatter="sizeFormatter" title="文件大小"></vxe-column>
                  <vxe-column field="updateDate" width="140" title="上传时间"></vxe-column>
                  <vxe-column field="file2Path" width="140" title="文件地址">
                    <template #default="{ row }">
                        <div @click="fuzhilianjie(row.file2Path)">{{row.file2Path}}</div>
                    </template>
                  </vxe-column>
                  <vxe-column field="filePath" min-width="180" title="文件" type="html" :formatter="urlFormater"></vxe-column>
                </vxe-table>
    
              </el-main>
        </vxe-modal>
    </div>
</template>

<script>
import {ref,reactive,toRefs} from "vue"
import XEUtils from 'xe-utils'
import { ElMessage, ElMessageBox } from 'element-plus'
import {DocumentChecked,Finished,DeleteFilled,ArrowDown} from '@element-plus/icons-vue'
import VXETable from 'vxe-table'
import {addFiles,getFile} from "/@/api/linkoo/form/index"
import {parseTime} from "/@/utils/ruoyi"
export default {
    props:['isequipment','showedit'],
    emits:["submit"],
    setup(props,ctx) {
        let FileTable = ref(null)
        let state =reactive({
            screenWidth: document.body.clientWidth,
            showDialog:false,
            sidShow:false,
            Data:{},
            Files:[],
            tableData: [],
            keyword: "",
            multiple:true,
            loading:false,
            DS:true,
            fileType:'files',
            title:'',
            fileSize:4,
            dataTypeID:0,
            extData:[],
            status:0
        })
        const todo=()=>{
            const value=state.Data.value
            if(value!==''&&value!==null&&value!==undefined){
                getFiles(value)
            }
            state.showDialog=true
            state.extData=[]
        }
        const getFiles=(ids)=>{
            getFile(ids).then(response => {
                state.tableData=response.data.files
            })
        }
        const selectFile=()=> {
            const cfg={}
            cfg['multiple']=state.multiple
            if(state.fileType==='images'){
                cfg['types']=['jpg','jpeg','png','tif','bmp','gif','pdf']
            }
            if(!state.multiple&&state.tableData.length>=1){
                ElMessage({
                        type: 'info',
                        message: `此字段只能有一个文件!`,
                    })
                return
            }
             VXETable.readFile(cfg).then(params => {
                const {files} = params
                const recod = Array.from(files).map(file => {
                if(file.size<=state.fileSize*1024*1024){
                    state.Files.push(file)
                    console.log("123456",state.Files);
                }
                return {
                    fileName: file.name,
                    fileSize: file.size,
                    updateDate: parseTime(new Date() ),
                    filePath:file.size>state.fileSize*1024*1024?file.name+' 文件超出'+state.fileSize+'M大小.上传时跳过!':''
                }
                })
                state.tableData = state.tableData.concat(recod)
            })
        }
        const uploadFile=()=>{
            let forms = new FormData()
            if(state.Files.length<1){
                ElMessage({
                        type: 'info',
                        message: `请先选择文件!`,
                    })
                return
            }
            state.loading=true
            state.Files.forEach(file=>{
                forms.append('file', file)
                forms.append('filesize[]', file.size)
                forms.append('filename[]', file.name)
            })
            let err=[]
          addFiles(forms).then(res => {
                state.tableData=  state.tableData.concat(res.data.files)
                XEUtils.remove( state.tableData, item => item.filePath === ''||item.filePath.indexOf('上传时跳过')>-1)
                if(state.dataTypeID===10){
                    state.extData=[]
                for(let i=0;i<res.data.length;i++){
                    state.loading=true
                    getBaiduOcr(res.data[i].fileID).then(res=>{
                    if(res.code===0){
                        if(res.data!==null){
                            state.extData=state.extData.concat(res.data)
                        }
                    }else{
                        ElMessage({
                        type: 'info',
                        message: '图像识别出错：'+res.msg,
                    })
                        err.push(1)
                    }
                    state.DS=err.length > 0
                    state.loading=false
                    })
                }
                }else{
                    state.loading=false
                }
                state.DS=err.length > 0
                state.Files=[]
            })

        }
        const deleteFile=() =>{
            const rows=FileTable.value.getCheckboxRecords()

            rows.forEach(row=>{
                const filerow=state.Files.find(item=>item.name===row.fileName)
                state.Files.splice(state.Files.indexOf(filerow),1)
                FileTable.value.remove(row)
            })

            let records= FileTable.value.getTableData().fullData
            state.tableData=records
          state.DS=false
        }
        const close=()=>{
            state.showDialog=false
            state.tableData=[]
            state.Files=[]
        }
        const submit=()=>{
            let records=Array.from(FileTable.value.getTableData().fullData).map(row=>{
                return row.fileID
            })
            let names=Array.from(FileTable.value.getTableData().fullData).map(row=>{
                return row.fileName
            })
            ctx.emit("submit", {data: records.join(','),filesName:names.join(','),extdata:state.extData});
            close()
        }
        const sizeFormatter=({cellValue })=>{
            return (cellValue/1024/1024).toFixed(2).toString()+'M'
        }
        const urlFormater=({cellValue,row })=>{
            console.log(row);
            if(cellValue.indexOf('./data/')>-1){
                return"<a target='_blank' href='"+cellValue+"'>查看</a>"
            }
        }
        const fuzhilianjie = (row)=>{
            console.log(row);
            if(row){
                const textarea = document.createElement('textarea');
                textarea.value =row
                document.body.appendChild(textarea);
                
                textarea.select();
                const successful = document.execCommand('copy');
                
                document.body.removeChild(textarea);
                if (successful) {
                        ElMessage({
                        type: 'success',
                        message: `复制成功`,
                    })
                } else {
                    ElMessage({
                        type: 'error',
                        message: `复制成功`,
                    })
                }
            }  
        }
        return{
            FileTable,
            ...toRefs(state),fuzhilianjie,
            getFiles,
            todo,
            selectFile,
            uploadFile,
            deleteFile,
            close,
            submit,
            urlFormater,
            sizeFormatter,
            DocumentChecked,
            Finished,
            DeleteFilled,
            ArrowDown
        }
    }
}
</script>

<style scoped>
  .el-aside {
    height: calc(100vh - 63px);
    background-color: #fff;

    padding: 0;
    margin: 0;
  }
  .el-header {
    background-color: #fff;
    color: #333;
    height: auto !important;
    padding: 0 10px;
  }
  .el-main {
    padding: 0 10px;
  }

  .vxe-pager--right-wrapper{float: right !important;}
  .vxe-modal--content{overflow-y: hidden !important;}
</style>